<?php

    if (!defined('BASEPATH'))
        exit('No direct script access allowed');

    /*
     * Glavna klasa - controler - komunicira sa servisima
     */

    class Main extends CI_Controller {

        public function __construct() {
            parent::__construct();

            // Load the rest client spark
            $this->load->spark('restclient/2.1.0');

            $this->rest->initialize(array(
                'server' => REST_URL,
                'http_user' => 'cipa',
                'http_pass' => 'booking',
                'http_auth' => 'basic' // or 'digest' 
            ));

            $this->activeLang = $this->lang->lang();

            require_once './application/libraries/urlify.php';

            $this->load->driver('cache', array('adapter' => 'file')); // za uklucuvanje na kes mogucnosti

            $this->lang->load('common');
        }

        public function index() {
            $this->home();
        }

        /*
         * Home page
         * 
         * @params : 
         *      input ('popular', 'visited', 'specialHotels', 'specialDests', 'recommended', 'googlemap','recentlybooked')
         */

        public function home() {

            $home_page = array('recommended', 'specialHotels', 'specialDests', 'popular', 'visited', 'googlemap');

            $file = cache_filename(array('lang' => $this->activeLang), 'combined');

            if (!$combined = $this->cache->get($file)) {

                $combined = $this->rest->post(
                        'home', array('lang' => $this->activeLang, 'input' => $home_page));

                if (DO_CACHE)
                    $this->cache->save($file, $combined, 1200);
            }
            
//            $this->firephp->log($combined);

            foreach ($home_page as $key)    // copy results to $data
                $data[$key] = $combined->{$key};

            if (isset($data['googlemap']))  // parse array of objects with coordinates
                $data['googlemap'] = make_google_map($data['googlemap']);

            $data['title'] = "Welcome";

            $data = currency_convert($data);    // Convert currency

            $this->template->load('home/home', $data);
        }

        /*
         * Autocomplete
         * 
         * @params : 
         *      name_startsWith
         *      plus_hotels
         * 
         */

        public function destinations_hotels_JSON($plus_hotels = FALSE) {

            $rest_data = array(
                "name_startsWith" => $_GET['name_startsWith'],
                "plus_hotels" => $plus_hotels,
                "lang" => $this->activeLang
            );

            $file = cache_filename($rest_data, 'combined');

            if (!$items = $this->cache->get($file)) {

                $items = $this->rest->post("destinationsHotelsAutocomplete", $rest_data);

                if (DO_CACHE)
                    $this->cache->save($file, $items, 1200);
            }

            // parse each row to regular array
            if ($plus_hotels):
                $myItems = array();
                foreach ($items as $value)
                    $myItems[] = get_object_vars($value);       // convert STD to Array

                $cnt = count($myItems); //trip whitespace
                for ($index = 0; $index < $cnt; $index++) :
                    $myItems[$index]['name'] = trim($myItems[$index]['name']);
                    $myItems[$index]['label'] = trim($myItems[$index]['label']);

                endfor;

                // sort
                sort_array_of_array($myItems, 'name', TRUE);
                $items = $myItems;
            endif;

            //echo JSON to page  
            $response = $_GET["callback"] . "(" . json_encode(array('items' => $items)) . ")";
            echo $response;
        }

        /*
         * Search page
         * 
         * @params:
         *      check_in
         *      check_out
         *      nr_adults
         *      ages
         *      dest_hot
         * 
         */

        public function search() {

            if (isset($_GET['preview']))
                $rest_method = 'searchPreview';
            else
                $rest_method = 'search';

            $file = cache_filename($_GET, 'results');

//            $this->firephp->log($rest_method);
//            $this->firephp->log($_GET);

            if (!$data['results'] = $this->cache->get($file)) {

                $data['results'] = $this->rest->post($rest_method, array_merge($_GET, array('lowestPricePreview' => TRUE)));

                if (DO_CACHE)
                    $this->cache->save($file, $data['results'], 1200);
            }
            //            $this->firephp->log($_GET);
            //            $this->firephp->log($data['results']);
            if (isset($_GET['acc_type']))
                filter_acc_type($data['results'], $_GET['acc_type']);

            loadJoinedGroupsAttributes($data['results']);

            $items = $rest_method == 'search' ? make_sort_price_available($data['results']) : $data['results'];
            $data['items'] = json_encode($items);
            $data['unique'] = findUniqueMakeCount($data['results']); // find unique filter attributes
            $data['unique_prices'] = findUniquePricesMakeCount($data['results'], isset($_GET['preview'])); // find unique prices for filter
            $data['unique_stars'] = findUniqueStarsMakeCount($data['results']); // find unique stars for filter
            // sort, splice and shuffle facilities & services
            sort_attributes($data['unique']);
            if (count($data['unique']) > 23)
                array_splice($data['unique'], 23);

            shuffle($data['unique']);

            // sort stars array
            ksort($data['unique_stars']);

            // load objects for maps
            $data['googlemap'] = make_google_map($data['results']);

//            $this->load->helper('search_seo');
//            $data['seo_title'] = search_title();
//            $data['seo_description'] = search_description();
//            $data['seo_keywords'] = lang('keywords-home');
//            $data['h1_title'] = search_h1();
//            $this->firephp->log($data);
            $data['title'] = "Hotels list";

            $data = currency_convert($data);    // Convert currency

            $this->template->load('booking/hotels-list', $data);
        }

        /*
         * Object details with rooms and prices
         * 
         * @params:
         *      check_in
         *      check_out
         *      nr_adults
         *      ages
         *      hotel_id
         * 
         */

        public function accommodation($i) {

            if (isset($_GET['preview']))
                $rest_method = 'detailsPreview';
            else
                $rest_method = 'details';

            $id = explode('-', $i);
            $ide = $id[count($id) - 1];

            $_GET['hotel_id'] = $ide;

//            $this->firephp->log($_GET);
//            $this->firephp->log($rest_method);

            $data['object'] = $this->rest->post($rest_method, $_GET);

            // load objects for maps
            $data['googlemap'] = make_google_map(array($data['object']));

            $data['title'] = $_GET['dest_hot'] = $data['object']->object_name;

            $data = currency_convert($data);    // Convert currency

            $this->template->load('booking/hotel-details', $data);
        }

        public function subscribe() {

            $rest_data = array(
                "email" => $_GET['subscribe_input']
            );

            $items = $this->rest->post("subscribe", $rest_data);

            echo json_encode(array('success' => TRUE));
        }

        public function submit_review() {

            $rest_data = $_GET;

            $success = $this->rest->post("submitReview", $rest_data);

            echo json_encode(array(
                'success' => $success
            ));
        }

        public function general_terms() {

            $this->data['title'] = "Terms and conditions";
            $this->template->set_view('terms_conditions');
            $this->template->load('terms_conditions/terms', $this->data);
        }

        public function terms_and_conditions() {

            $this->data['title'] = "Terms and conditions";

            $rest_data = array(
                "hotel_id" => $this->input->get('hotel_id'),
                "room_id" => $this->input->get('room_id'),
                "lang" => $this->lang->lang()
            );

            $this->data['terms_conditions'] = $this->rest->post("termsConditions", $rest_data);

//            $this->firephp->log($this->data['terms_conditions']);


            $this->template->set_view('terms_conditions');
            $this->template->load('terms_conditions/conditions', $this->data);
        }

        /*
         * Cancel reservation view
         */

        public function reservation_cancellation() {

            $this->data['title'] = "Reservation Cancellation";
            $this->data['reservation_ID'] = $this->input->get('reservation_ID');
            $this->template->load('reservation/cancel', $this->data);
        }

        /*
         * Cancel reservation confirm
         */

        public function cancellation_confirmation() {

            $this->data['title'] = "Cancellation Confirmation";
            $this->data['reservation_ID'] = $this->input->get('reservation_ID');
            $result = $this->rest->post("cancelReservation", array('reservation_ID' => $this->data['reservation_ID']));

//            $this->firephp->log($result);
            $this->template->load('reservation/cancellation_confirmation', $this->data);
        }

    }

?>
